package main

import (
	"embed"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"go.uber.org/zap"
	"html/template"
	"net/http"
	"time"
)

//go:embed template/*
var templates embed.FS

//go:embed static/*
var static embed.FS

func router() {
	//wg.Add(1)
	t, _ := template.ParseFS(templates, "template/*.html")
	r := gin.Default()
	r.SetHTMLTemplate(t)
	r.StaticFS("/public", http.FS(static))
	r.GET("/", Hello)
	r.GET("/ws", wsFun)
	err := r.Run()
	if err != nil {
		logger.Error("启动web服务错误：", zap.Error(err))
	}
	//wg.Done()
}

func Hello(c *gin.Context) {
	c.HTML(http.StatusOK, "index.html", nil)
}

var upGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func wsFun(c *gin.Context) {
	origin := c.Request.Header.Get("Origin")
	fmt.Println(origin)
	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		logger.Error("升级websocket失败", zap.Error(err))
	}
	defer ws.Close()
	for {
		dataType, _ := json.Marshal(clientList)
		data := string(dataType)
		err = ws.WriteMessage(websocket.TextMessage, []byte(data))
		if err != nil {
			logger.Error("写入数据错误", zap.Error(err))
			break
		}
		time.Sleep(time.Second)
	}
}
